import Dialog from '@vant/weapp/dialog/dialog';
import { goodsForCart } from "../../data/goods";
const app =  getApp();
Page({
  data:{
    isLoading:true,
    selectedAll:true,
    goods:[],
    numForCommit:0,
    totalPrice:0,
    
  },
  onLoad(option) {
    let goods=goodsForCart();
    if(option.from=='detail'){
      goods.unshift(app.gData.goodsDetail);
    }
    this.setData({goods:goods});
    this.updateGoodsData(this);
    setTimeout(()=>{
      this.setData({isLoading:false});
    },1000);
  },
  toHome(e) {
    wx.navigateTo({url: '/pages/home/index'});
  },
  toSettle(e) {
    if(this.data.totalPrice<=0)return;
    let goods=this.data.goods.filter(item=>item.numBuys>0);
    app.gData.goodsForCommit=goods;
    wx.navigateTo({url: 'commit/index',});
  },
  toMore(e) {
    wx.navigateTo({url: 'more/index',});
  },
  onSelectAll(e) {
    //console.log('onSelectAll:',e.detail);
    this.setData({selectedAll:!this.data.selectedAll});
    this.updateGoodsData(this,'select_all',e.detail);
  },
  onCBChange(e) {
    this.updateGoodsData(this,'change_cb',e.detail);
  },
  onDeleteGoods(e) {
    console.log('onDeleteGoods:',e.detail);
    this.updateGoodsData(this,'delete_goods',{id:e.detail.id});
  },
  onStepGoods(e) {
    //console.log('onStepGoods:',e);
    if(e.detail.count<=0){
      const card = this.selectComponent('#'+e.currentTarget.id);
      Dialog.confirm({
        message: '确定删除该商品',
      }).then(() => {
        //console.log('onStepGoods confirm');
        this.updateGoodsData(this,'delete_goods',{id:e.detail.id});
      }).catch(() => {
        //console.log('onStepGoods cancel');
        card.setCount(1);
      });
    }else{
      this.updateGoodsData(this,'step_goods',{id:e.detail.id,count:e.detail.count});
    }
  },
  updateGoodsData(that,type,value){
    //console.log('updateGoodsData:');
    let i;
    let arr=that.data.goods;
    if(type=="select_all"){
      for(i=0;i<arr.length;i++)
        arr[i].selected=value;
    }
    if(type=="step_goods"){
      for(i=0;i<arr.length;i++){
        if(arr[i].id==value.id)arr[i].numBuys=value.count;
      }
    }
    if(type=="delete_goods"){
      arr=arr.filter(item=>item.id!=value.id);
    }
    if(type=="change_cb"){
      for(i=0;i<arr.length;i++){
        if(arr[i].id==value.id)arr[i].selected=value.selected;
      }
    }
    //console.log(arr);
    let _numForCommit=0;
    for(i=0;i<arr.length;i++){
      if(arr[i].selected) _numForCommit+=arr[i].numBuys;
    }
    that.setData({numForCommit:_numForCommit});
    let _totalPrice=0;
    for(i=0;i<arr.length;i++){
      if(arr[i].selected) _totalPrice+=arr[i].price*arr[i].numBuys;
    }
    that.setData({totalPrice:_totalPrice});
    //
    that.setData({goods:arr});
  },
})
